import { Injectable } from "@angular/core";
import { Device } from "@ionic-native/device";
import { CryptoService } from "./crypto.service";

/**
 * 配置项存储服务类
 * 
 * (需要在AppModule中全局注入)
 * 
 * @export
 * @class ConfigurationService
 */
@Injectable()
export class ConfigurationStoreService {

    private passphrase: string;

    constructor(private crypto: CryptoService, private device: Device) {
        let uuid: string = "default value used in browser";
        const isApp = document.URL.indexOf('http://') === -1 && document.URL.indexOf('https://') === -1;
        if (isApp) {
            // Cordova application
            uuid = this.device.uuid;
        }

        this.passphrase = this.crypto.md5.digest(uuid);
    }

    /**
     * 获取参数配置项
     * 
     * @param {string} key 配置项名称
     * @returns {string} 配置项内容
     * @memberof ConfigurationService
     */
    public getItem(key: string, cipher: boolean = true): string {
        const stored: string = localStorage.getItem(key);
        if (!cipher) {
            return stored;
        }
        const dec = this.crypto.aes.decrypt(stored, this.passphrase);
        return dec;
    }

    /**
     * 保存参数配置项
     * 
     * @param {string} key 配置项名称
     * @param {string} value 配置项内容
     * @memberof ConfigurationService
     */
    public setItem(key: string, value: string, cipher: boolean = true) {
        // 不保存undefined
        if (typeof value === "undefined") {
            return;
        }
        if (!cipher) {
            localStorage.setItem(key, value);
            return;
        }
        const enc = this.crypto.aes.encrypt(value, this.passphrase);
        localStorage.setItem(key, enc);
    }

    /**
     * 删除参数配置项
     * 
     * @param {string} key 配置项名称
     * @memberof ConfigurationStoreService
     */
    public removeItem(key: string) {
        localStorage.removeItem(key);
    }
}
